#include "stm32f4xx.h"
#include <stdint.h>
#include <stdbool.h>
#include <string.h>
#include "console_timer.h"

void timer_init(uint16_t arr, uint16_t psc)
{
    RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM2, ENABLE);
    
    TIM_TimeBaseInitTypeDef TIM_TimeBaseInitStructure;

    // TIM_TimeBaseInitStructure结构体清零
    memset(&TIM_TimeBaseInitStructure, 0, sizeof(TIM_TimeBaseInitTypeDef));

    TIM_TimeBaseInitStructure.TIM_ClockDivision = TIM_CKD_DIV1;
    TIM_TimeBaseInitStructure.TIM_CounterMode = TIM_CounterMode_Up;
    TIM_TimeBaseInitStructure.TIM_Period = arr;
    TIM_TimeBaseInitStructure.TIM_Prescaler = psc;
    TIM_TimeBaseInitStructure.TIM_RepetitionCounter = 0;
    TIM_TimeBaseInit(TIM2,&TIM_TimeBaseInitStructure);
}

void timer_delay_us(uint32_t us)
{
    TIM2->ARR = us;     /* 自动重装载寄存器值为us */
    TIM2->CNT = 0;      /* 设定CNT初始计数值为0 向上计数模式 */
    TIM_Cmd(TIM2,ENABLE);
    while( TIM2->CNT < us);
    TIM_Cmd(TIM2,DISABLE);
}

void timer_delay_ms(uint32_t ms)
{
    for(int i = 0;i<ms;i++)
    {
        timer_delay_us(1000);
    }    
}

